const mysql = require('../utils/mysql_util');
const prodMysql = require('../utils/prod_mysql_util');
const mongod = require('../utils/mongod_util');
const prodMongod = require('../utils/prod_mongod_util');
const projectJson = require('../mongod/project_json');
const prodProjectJson = require('../mongod/prod_project_json');
const squel = require('squel');
const fs = require('fs');
const path = require('path');

// const gridFs = mongod.gridFs;
// const copyGridFs = prodMongod.gridFs;
// const projectJson = mongod.ProjectJson;
// const prodProjectJson = prodMongod.ProjectJson;
const eachLimit = require('async/eachLimit');


/**
 * 保存方案考出记录信息
 * @param designId
 * @param gmt_create
 */
const saveCopyInfo = (designId, gmt_create) => new Promise((res, rej) => {
  prodMysql.execute(`delete from copyProjectToDev where designId='${designId}'`).then(() => {
    prodMysql.execute(`INSERT into copyProjectToDev (designId,gmt_create)VALUES('${designId}','${gmt_create}')`)
      .then(() => {
        console.log(`保存${designId}原始记录成功！`);
        res();
      }).catch((err1) => {
        console.log(`保存${designId}原始记录失败！`);
        rej(err1);
      });
  }).catch((err) => {
    console.log(`删除${designId}拷贝记录失败！`);
    rej(err);
  });
});

const saveProject = project => new Promise((res, rej) => {
  mysql.execute(`delete from project where  designId='${project.designId}'`).then(() => {
    mysql.execute(squel.insert().into('project').setFields(project).toString()).then(() => {
      console.log(`保存${project.designId}方案属性数据成功！`);
      res();
    }).catch((err1) => {
      console.log(`保存${project.designId}方案属性数据失败！`);
      rej(err1);
    });
  }).catch((err) => {
    console.log(`删除${project.designId}原始记录失败！`);
    rej(err);
  });
});

/**
 * 保存方案data数据（json字符串），保存到mongodb，同时维护最新50个版本记录
 * @param strDesignJson
 * @param designId
 * @param userId
 */
const saveDesignJson = (strDesignJson, designId, userId) =>
  new Promise((res, rej) => {
    // 查询获取最新版本编号
    let maxVersion;
    const projectVersionSql = `select max(version) as max from project_version where designId='${designId}' `;
    mysql.execute(projectVersionSql)
      .then((result) => {
        if (result && result[0] && result[0].max) {
          maxVersion = result[0].max + 1;
        } else {
          maxVersion = 1;
        }
        const designjson = new projectJson();
        designjson.projectData = strDesignJson;
        designjson.projectVersion = maxVersion.toString();
        designjson.projectDesignId = designId;
        designjson.userId = userId;
        // 将方案json数据保存到mongodb，
        designjson.save((err, resultDesignJson) => {
          if (err) {
            console.log(`保存${designId}方案Json数据失败！`);
            rej(err);
          } else {
            console.log(`保存${designId}方案Json数据成功！`);
            // 保存新版本信息
            const insertProjectVersion = `INSERT into project_version (designId,mongo_key,version)VALUES
            ('${designId}','${resultDesignJson._id.toString()}','${maxVersion}')`;
            mysql.execute(insertProjectVersion).then(() => {
              console.log(`保存${designId}方案Json版本信息成功！`);
              res();
            }).catch((err) => {
              console.log(`保存${designId}方案Json版本信息失败！`);
              rej(err);
            });
          }
        });
      })
      .catch((err) => {
        if (err) rej(err);
      });
  });

/**
 * 通过方案或户型编码，获取最新json数据
 * @param designId
 */
const copyAndSaveDesignJson = (designId, userId) => new Promise((res, rej) => {
  // const dataMap = {};
  const projectVersionSql = `select mongo_key from project_version where designId='${designId}' and ` +
    `version= (select max(version) from project_version where designId='${designId}')`;
  prodMysql.execute(projectVersionSql)
    .then((projectVersion) => {
      if (projectVersion && projectVersion[0]) {
        prodProjectJson.find({ _id: projectVersion[0].mongo_key }, (err, projectJsonData) => {
          if (err) {
            console.log(`读取${designId}方案Json数据失败！`);
            rej(err);
          }
          if (projectJsonData && projectJsonData[0]) {
            console.log(`读取${designId}方案Json数据成功！`);
            res(saveDesignJson(projectJsonData[0]._doc.projectData, designId, userId));
          } else {
            res();
          }
        });
      } else {
        res();
      }
    })
    .catch((err) => {
      if (err) rej(err);
    });
});

/**
 * mongodb gridFs图片复制
 * @param oldName
 * @param newName
 */
const copyAndSaveImage = imageName => new Promise((res, rej) => {
  prodMongod.gridFs().then((result) => {
    const readStream = result.createReadStream({
      filename: imageName,
      root: 'project_image'
    });
    readStream.on('error', (err1) => {
      console.log(`读取${imageName} 图片失败！`);
      res();
    });

    mongod.gridFs().then((result) => {
      const writeStream = result.createWriteStream({
        filename: imageName,
        root: 'project_image'
      });
      writeStream.on('close', () => {
        console.log(`完成${imageName} 图片拷贝！`);
        res();
      });

      writeStream.on('error', (err2) => {
        console.log(`写入${imageName} 图片失败！`);
        res();
      });
      if (readStream) { readStream.pipe(writeStream); }
    });
  });
});

/**
 * 将生产环境的Project信息拷贝到开发环境
 */
exports.copyProdProjectToDev = () => {
  const queryProject = "select a.*,DATE_FORMAT(a.gmt_create, '%Y-%m-%d %T') as gmtCreate from project a " +
    'right JOIN copyProjectToDev b on a.designId=b.designId ' +
    'where  asset_type=2 and `status`!=10    ';
    // 'and a.designId="b20348cc-79fa-49dc-ba1f-c26c55fdc814"';

  prodMysql.execute(queryProject).then((copyProjectList) => {
    // 异步，一次执行10个
    eachLimit(copyProjectList, 10, (copyProject, callback) => {
      delete copyProject.id;
      const designId = copyProject.designId;
      const gmt_create = copyProject.gmtCreate;
      delete copyProject.gmt_create;
      delete copyProject.gmt_modified;
      delete copyProject.gmtCreate;
      Promise.all([
        // 拷贝截图和top图
        // copyAndSaveImage(`${designId}_jt.jpg`),
        // copyAndSaveImage(`${designId}_top3D.jpg`),
      // 拷贝Json，方案数据
        copyAndSaveDesignJson(designId, copyProject.user_id),
      // 拷贝方案属性数据
        saveProject(copyProject)

      ]).then(() => {
        // 保存数据导入过程信息
        saveCopyInfo(designId, gmt_create).then(() => {
          setImmediate(callback);
        }).catch((err1) => {
          setImmediate(callback);
        });
      }).catch((err) => {
        setImmediate(callback);
      });
    });
  }).catch((err) => {
    throw err;
  });
};




/**
 * 下载方案信息
 */
exports.downloadProjectInfo = () => {
  const queryProject = "SELECT * FROM project WHERE user_login LIKE 'cdhx%' AND `status` = 0 and asset_type = 4" ;

  prodMysql.execute(queryProject).then((copyProjectList) => {
    // 异步，一次执行10个
    eachLimit(copyProjectList, 10, (copyProject, callback) => {
      const designId = copyProject.designId;
      request(`http://10.19.176.174:20091/project/open?d=${designid}`, (error, response, body) => {
        const data = JSON.parse(body).data;
        fs.writeFile(`E://project/${designid}.json`, data, { flag: 'a' }, (err) => {
          if (err) {
            setImmediate(callback);
          } else {
            setImmediate(callback);
          }
        });
        callback();
      });
    });
  }).catch((err) => {
    throw err;
  });
};

